package com.algorithms;

/**
 * 二分查找法
 */
public class BinarySearch {

    public static int rank(int key, int[] a) {//数组必须是有序的
        int lo = 0;
        int hi = a.length - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) hi = mid - 1;         //在左边
            else if (key > a[mid]) lo = mid + 1;    //在右边
            else return mid;
        }
        return -1;
    }

    public static void main(String[] args) {
        int [] a = {3,7,8,12,45,102,111,245};
        System.out.println(rank(102,a));
    }

}
